<?php

use App\Exceptions\SwooleExitException;
use App\Services\EncodeIdService;
use App\Services\ResultCodeService;
use App\Services\SmsService;
use Illuminate\Http\Exceptions\HttpResponseException;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\Log;

if (!function_exists('helper_service')) {
    function helper_service()
    {

        return  new \App\Services\HelperService();
    }
}

if (!function_exists('import_excel')) {
    function import_excel($fileUrl, $typeName)
    {
        return helper_service()->import_excel($fileUrl, $typeName);
    }
}

if (!function_exists('downloadFile')) {
    function downloadFile($url, $savePath)
    {
        return helper_service()->downloadFile($url, $savePath);
    }
}

if (!function_exists('create_randomstr')) {
    function create_randomstr($lenth = 6)
    {
        return helper_service()->create_randomstr($lenth);
    }
}

if (!function_exists('qiniu_upload')) {
    function qiniu_upload($url, $fileName, $ext)
    {
        return helper_service()->qiniuUplode($url, $fileName, $ext);
    }
}

if (!function_exists('get_qiniu_list')) {
    function get_qiniu_list($marker = '')
    {
        return helper_service()->getQiniuList($marker);
    }
}

if (!function_exists('member')) {
    function member()
    {
        return helper_service()->member();
    }
}

if (!function_exists('memberId')) {
    function memberId()
    {
        return helper_service()->memberId();
    }
}

if (!function_exists('responses')) {
    function responses($message = '', $data = [], $code = 200)
    {
        $result['data'] = $data;


        $result['data'] = $data;

        $result['code'] = $code;

        $result['message'] = $message;
        // header('Content-Type:application/json; charset=utf-8');

        // exit(json_encode($result));
        return response()->json($result)->header('Content-Type', 'application/json;charset=UTF-8')->setEncodingOptions(JSON_UNESCAPED_UNICODE);

        // return ResultCodeService::apply($message, $code, $data);
    }
}

if (!function_exists('success')) {
    function success($data = [], $message = '操作成功', $code = 200)
    {
        return responses($message, $data, $code);
    }
}

if (!function_exists('fail')) {
    function fail($data = [], $message = '操作失败', $code = 422)
    {
        return responses($message, $data, $code);
    }
}

if (!function_exists('fail_message')) {
    function fail_message($message = '操作失败')
    {
        throw new HttpResponseException(fail([], $message));
    }
}

if (!function_exists('success_message')) {
    function success_message($message = '操作成功')
    {
        return success([], $message);
    }
}

if (!function_exists('info_array')) {
    function info_array($info = [], $follow_id = [], $chooes_id = [])
    {
        return helper_service()->infoArray($info, $follow_id, $chooes_id);
    }
}


if (!function_exists('exportExcel')) {
    function exportExcel($header, $title, $list, $width)
    {
        return helper_service()->exportExcel($header, $title, $list, $width);
    }
}

// 发送验证码
if (!function_exists('sendCode')) {
    function sendCode($phone, $code, $template)
    {
        return SmsService::sendCode($phone, $code, $template);
    }
}


// laravel 加密ID
if (!function_exists('idToString')) {
    function idToString($id)
    {
        $obj = new EncodeIdService();
        return $obj->idToString($id);
    }
}

// laravel 解密ID
if (!function_exists('stringToId')) {
    function stringToId($string)
    {
        $obj = new EncodeIdService();
        return $obj->stringToId($string);
    }
}


// 记录错误日志
if (!function_exists('errorLog')) {
    function errorLog($e)
    {
        Log::error(json_encode($e));
    }
}

// 记录警告日志
if (!function_exists('warningLog')) {
    function warningLog($e)
    {
        Log::warning(json_encode($e));
    }
}

// 记录通知日志
if (!function_exists('noticeLog')) {
    function noticeLog($e)
    {
        Log::notice($e);
    }
}

// 记录信息日志
if (!function_exists('infoLog')) {
    function infoLog($e)
    {
        Log::info($e);
    }
}

// 记录信息日志
if (!function_exists('qnUrl')) {
    function qnUrl()
    {
        return config('filesystems.disks.qiniu.domains.https');
    }
}


if (!function_exists('user_admin_config')) {
    function user_admin_config($key = null, $value = null)
    {
        $session = session();
        if (!$config = $session->get('admin.config')) {
            $config = config('admin');

            $config['lang'] = config('app.locale');
        }

        if (is_array($key)) {
            // 保存
            foreach ($key as $k => $v) {
                Arr::set($config, $k, $v);
            }

            $session->put('admin.config', $config);

            return;
        }

        if ($key === null) {
            return $config;
        }

        return Arr::get($config, $key, $value);
    }
}

// 获取后缀名
if (!function_exists('getExt')) {
    function getExt($url)
    {
        if (isset($url) && !empty($url)) {
            return pathinfo(parse_url($url)['path'])['extension'];
        }
    }
}

/**
 * @ 0-存数字字符串；1-小写字母字符串；2-大写字母字符串；3-大小写数字字符串；4-字符；
 *   5-数字，小写，大写，字符混合
 * @param  integer $type   [字符串的类型]
 * @param  integer $length [字符串的长度]
 * @param  integer $time   [是否带时间1-带，0-不带]
 * @return [string]  $str    [返回唯一字符串]
 */
if (!function_exists('randSole')) {
    function randSole($type = 0, $length = 18, $time = 0)
    {
        $str = $time == 0 ? '' : date('YmdHis', time());
        switch ($type) {
            case 0:
                for ((int) $i = 0; $i <= $length; $i++) {
                    if (mb_strlen($str) == $length) {
                        $str = $str;
                    } else {
                        $str .= rand(0, 9);
                    }
                }
                break;
            case 1:
                for ((int) $i = 0; $i <= $length; $i++) {
                    if (mb_strlen($str) == $length) {
                        $str = $str;
                    } else {
                        $rand = "qwertyuioplkjhgfdsazxcvbnm";
                        $str .= $rand[mt_rand(0, 25)];
                    }
                }
                break;
            case 2:
                for ((int) $i = 0; $i <= $length; $i++) {
                    if (mb_strlen($str) == $length) {
                        $str = $str;
                    } else {
                        $rand = "QWERTYUIOPLKJHGFDSAZXCVBNM";
                        $str .= $rand[mt_rand(0, 25)];
                    }
                }
                break;
            case 3:
                for ((int) $i = 0; $i <= $length; $i++) {
                    if (mb_strlen($str) == $length) {
                        $str = $str;
                    } else {
                        $rand = "123456789qwertyuioplkjhgfdsazxcvbnmQWERTYUIOPLKJHGFDSAZXCVBNM";
                        $str .= $rand[mt_rand(0, 34)];
                    }
                }
                break;
            case 4:
                for ((int) $i = 0; $i <= $length; $i++) {
                    if (mb_strlen($str) == $length) {
                        $str = $str;
                    } else {
                        $rand = "!@#$%^&*()_+=-~`";
                        $str .= $rand[mt_rand(0, 16)];
                    }
                }
                break;
            case 5:
                for ((int) $i = 0; $i <= $length; $i++) {
                    if (mb_strlen($str) == $length) {
                        $str = $str;
                    } else {
                        $rand = "123456789qwertyuioplkjhgfdsazxcvbnmQWERTYUIOPLKJHGFDSAZXCVBNM!@#$%^&*()_+=-~`";
                        $str .= $rand[mt_rand(0, 51)];
                    }
                }
                break;
        }
        return $str;
    }
}


/**
 * 判断地址是否是url地址
 *
 * @Author hechengwei
 * @email chichiooo@sina.com
 * @DateTime 2022-04-11
 * @param string $url
 * @return bool
 */
if (!function_exists('or_url')) {
    function or_url($url)
    {

        if (empty($url)) {
            return true;
        }
        $preg = "/http[s]?:\/\/[\w.]+[\w\/]*[\w.]*\??[\w=&\+\%]*/is";

        if (preg_match($preg, $url)) {

            return true;
        } else {

            return false;
        }
    }
}




if (!function_exists('list_to_tree')) {
    /**
     * 把返回的数据集转换成Tree
     * @access public
     * @param array $array 要转换的数据集
     * @param string $pid parent标记字段
     * @param string $level level标记字段
     * @return array
     */
    function list_to_tree(array $array, string $first, string $pid, string $id, string $child = 'childs')
    {
        return helper_service()->list_to_tree($array, $first, $pid, $id, $child);
    }
}


if (!function_exists('list_sort_by')) {
    /**
     * 对查询结果集进行排序
     * @access public
     * @param array $list 查询结果
     * @param string $field 排序的字段名
     * @param array $sortby 排序类型
     * asc正向排序 desc逆向排序 nat自然排序
     * @return array
     */
    function list_sort_by($list, $field, $sortby = 'asc')
    {
        return helper_service()->list_sort_by($list, $field, $sortby);
    }
}

if (!function_exists('list_search')) {
    /**
     * 在数据列表中搜索
     * @access public
     * @param array $list 数据列表
     * @param mixed $condition 查询条件
     * 支持 array('name'=>$value) 或者 name=$value
     * @return array
     */
    function list_search($list, $condition)
    {
        return helper_service()->list_search($list, $condition);
    }
}

if (!function_exists('convert_arr_key')) {
    /**
     * @param $arr
     * @param $key_name
     * @return array
     * 将数据库中查出的列表以指定的 id 作为数组的键名
     */
    function convert_arr_key($arr, $key_name)
    {
        return helper_service()->convert_arr_key($arr, $key_name);
    }
}

if (!function_exists('get_id_val')) {
    /**
     * @param $arr
     * @param $key_name
     * @param $key_name2
     * @return array
     * 将数据库中查出的列表以指定的 id 作为数组的键名 数组指定列为元素 的一个数组
     */
    function get_id_val($arr, $key_name, $key_name2)
    {
        return helper_service()->get_id_val($arr, $key_name, $key_name2);
    }
}

if (!function_exists('flareout_array')) {
    /**
     *  PHP快速高效的将多维数组降维
     */
    function flareout_array($array)
    {
        return helper_service()->flareout_array($array);
    }
}

if (!function_exists('real_ip')) {
    function real_ip()
    {
        static $realip = NULL;
        if ($realip !== NULL) {
            return $realip;
        }
        if (isset($_SERVER)) {
            if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
                $arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
                foreach ($arr as $ip) {
                    $ip = trim($ip);
                    if ($ip != 'unknown') {
                        $realip = $ip;
                        break;
                    }
                }
            } elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
                $realip = $_SERVER['HTTP_CLIENT_IP'];
            } else {
                if (isset($_SERVER['REMOTE_ADDR'])) {
                    $realip = $_SERVER['REMOTE_ADDR'];
                } else {
                    $realip = '0.0.0.0';
                }
            }
        } else {
            if (getenv('HTTP_X_FORWARDED_FOR')) {
                $realip = getenv('HTTP_X_FORWARDED_FOR');
            } elseif (getenv('HTTP_CLIENT_IP')) {
                $realip = getenv('HTTP_CLIENT_IP');
            } else {
                $realip = getenv('REMOTE_ADDR');
            }
        }
        preg_match("/[\d\.]{7,15}/", $realip, $onlineip);
        $realip = !empty($onlineip[0]) ? $onlineip[0] : '0.0.0.0';
        return $realip;
    }
}
if (!function_exists('randCode')) {
    /**
     * @param  integer $length [字符串的长度]
     */
    function randCode($len)
    {
        return helper_service()->randCode($len);
    }
}




if (!function_exists('httpToHttps')) {
    /**
     * @param  integer $length [字符串的长度]
     */
    function httpToHttps($url)
    {
        return  str_replace("http://", "https://", $url);
    }
}
